import Toast from 'tdesign-miniprogram/toast/index';
import { fetchSettleDetail } from '../../../services/order/orderConfirm';
import { getAddressPromise } from '../../usercenter/address/list/util';

const app = getApp()
Page({
  data: {
    loading: false,
    settleDetailData: {
      storeGoodsList: [], //正常下单商品列表
    }, // 获取结算页详情 data
    orderCardList: [], // 仅用于商品卡片展示
    totalPrice: 0,
    goodsRequestList: [],
    userAddressReq: null,
    notesPosition: 'center',
    storeInfoList: [],
    userAddress: null,
  },

  payLock: false,
  noteInfo: [],
  tempNoteInfo: [],
  onLoad(options) {
    this.setData({
      loading: true,
    });
    this.handleOptionsParams(options);
  },
  onShow() {
    this.setData({
      userAddress: wx.getStorageSync('address') ? JSON.parse(wx.getStorageSync('address')) : null
    },()=>{
      wx.removeStorage({
        key: 'address',
      })
    })
  },

  init() {
    this.setData({
      loading: true,
    });
    const { goodsRequestList } = this;
    this.handleOptionsParams({ goodsRequestList });
  },
  // 处理不同情况下跳转到结算页时需要的参数
  handleOptionsParams(options) {
    let { goodsRequestList } = this; // 商品列表
    let { userAddressReq } = this; // 收货地址

    const storeInfoList = []; 
    // 如果是从地址选择页面返回，则使用地址显选择页面新选择的地址去获取结算数据
    if (options.userAddressReq) {
      userAddressReq = options.userAddressReq;
    }
    if (options.type === 'cart') {
      // 从购物车跳转过来时，获取传入的商品列表数据
      const goodsRequestListJson = wx.getStorageSync('order.goodsRequestList');
      goodsRequestList = JSON.parse(goodsRequestListJson);
    } else if (typeof options.goodsRequestList === 'string') {
      goodsRequestList = JSON.parse(options.goodsRequestList);
    }
    //获取结算页请求数据列表
    const storeMap = {};
    goodsRequestList.forEach((goods) => {
      if (!storeMap[goods.storeId]) {
        storeInfoList.push({
          storeId: goods.storeId,
          storeName: goods.storeName,
        });
        storeMap[goods.storeId] = true;
      }
    });
    this.goodsRequestList = goodsRequestList;
    this.storeInfoList = storeInfoList;
    fetchSettleDetail().then(
      (res) => {
        this.setData({
          loading: false,
        });
        let sum = 0
        res.forEach(item=>{
          sum += item.price
        })
        this.setData({ 
          orderCardList: res,
          totalPrice: sum
        });
      },
      () => {
        //接口异常处理
        this.handleError();
      },
    );
  },
  onGotoAddress() {
    /** 获取一个Promise */
    getAddressPromise()
      .then((address) => {
        this.handleOptionsParams({
          userAddressReq: { ...address, checked: true },
        });
      })
      .catch(() => {});

    const { userAddressReq } = this; // 收货地址

    let id = '';

    if (userAddressReq?.id) {
      id = `&id=${userAddressReq.id}`;
    }

    wx.navigateTo({
      url: `/pages/usercenter/address/list/index?selectMode=1&isOrderSure=1${id}`,
    });
  },
  onBlur() {
    this.setData({
      notesPosition: 'center',
    });
  },
  onFocus() {
    this.setData({
      notesPosition: 'self',
    });
  },
  // 提交订单
  submitOrder() {
    if (!this.data.userAddress) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请添加收货地址',
        duration: 2000,
        icon: 'help-circle',
      });
      return;
    }
    wx.cloud.database().collection('book-order').add({
      data:{
        state: 2,
        commodity: this.data.orderCardList,
        address: this.data.userAddress,
        totalPrice: this.data.totalPrice,
        orderNum: (Date.now()).toString()+(Math.trunc(Math.random()*100000)).toString(),
        userid: app.globalData.userInfo._id,
        _createTime: Date.now(),
        _updateTime: Date.now()
      }
    }).then(res=>{
      wx.setStorageSync('address', null)
      wx.navigateTo({
        url: `/pages/order/pay-result/index?totalPaid=${this.data.totalPrice}`,
      })
    })
  },
});
